using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.MaterialManage;
using RBAC.Domain.OutboundManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.OutboundManagement;
using RBAC.Write.Api.Application.Dto.ERP;

namespace RBAC.Write.Api.Application.Handler.ERP.OutboundManagement
{
    public class AddSalesOutboundHandler : IRequestHandler<AddSalesOutboundCommand, APIResult<long>>
    {
        private readonly IBaseRepository<SalesOutbound> outboundRepo;
        private readonly IBaseRepository<SalesOutboundDetail> detailRepo;
        private readonly IBaseRepository<Mater> materRepo;
        private readonly ILogger<AddSalesOutboundHandler> logger;

        public AddSalesOutboundHandler(
            IBaseRepository<SalesOutbound> outboundRepo,
            IBaseRepository<SalesOutboundDetail> detailRepo,
            IBaseRepository<Mater> materRepo,
            ILogger<AddSalesOutboundHandler> logger)
        {
            this.outboundRepo = outboundRepo;
            this.detailRepo = detailRepo;
            this.materRepo = materRepo;
            this.logger = logger;
        }

        public Task<APIResult<long>> Handle(AddSalesOutboundCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<long>();
            try
            {
                if (request.Data == null || request.Data.Details == null || request.Data.Details.Count == 0)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "明细不能为空";
                    result.Data = 0;
                    return Task.FromResult(result);
                }

                var dto = request.Data;
                var materIds = dto.Details.Select(d => d.MaterId).Distinct().ToList();
                var inClause = string.Join(",", materIds.Select((_, index) => $"@Id{index}"));
                var parameters = materIds.Select((id, index) => new { Key = $"@Id{index}", Value = id })
                    .ToDictionary(x => x.Key, x => (object)x.Value);
                var maters = materRepo.GetAll($"Id IN ({inClause})", parameters);
                var validMaterIds = new HashSet<long>(maters.Select(m => m.Id));
                var missing = materIds.Where(id => !validMaterIds.Contains(id)).ToList();
                if (missing.Any())
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = $"存在无效物料ID: {string.Join(",", missing)}";
                    result.Data = 0;
                    return Task.FromResult(result);
                }

                // 校验跟单编号（销售订单编号）是否已被引入
                var copyCodes = dto.Details
                    .Select(d => d.CopyTradCode)
                    .Where(s => !string.IsNullOrWhiteSpace(s))
                    .Distinct()
                    .ToList();
                if (copyCodes.Count > 0)
                {
                    var inClause2 = string.Join(",", copyCodes.Select((_, i) => $"@C{i}"));
                    var param2 = copyCodes.Select((c, i) => new { Key = $"@C{i}", Value = (object)c })
                        .ToDictionary(x => x.Key, x => x.Value);
                    var exists = detailRepo.GetAll($"CopyTradCode IN ({inClause2}) AND IsDeleted = false", param2)
                        .Select(x => x.CopyTradCode)
                        .Where(s => !string.IsNullOrWhiteSpace(s))
                        .Distinct()
                        .ToList();
                    if (exists.Any())
                    {
                        result.Code = APIEnums.Fail;
                        result.Msg = $"{string.Join(",", exists)}已引入，不可重复引入";
                        result.Data = 0;
                        return Task.FromResult(result);
                    }
                }

                var now = DateTime.Now;
                var headerSql = @"START TRANSACTION;
INSERT INTO SalesOutbound (OrderCode, OrderType, BusinessType, Period, CustomerCode, CustomerName, OrderDate, BusinessStatus, Warehouse, OrderStatus, DeliveryNo, DeliveryType, BusinessDept, BusinessPerson, Remark, CreateUser, CreateTime, IsDeleted)
VALUES (@OrderCode, @OrderType, @BusinessType, @Period, @CustomerCode, @CustomerName, @OrderDate, @BusinessStatus, @Warehouse, @OrderStatus, @DeliveryNo, @DeliveryType, @BusinessDept, @BusinessPerson, @Remark, @CreateUser, @CreateTime, false);
SET @hid = LAST_INSERT_ID();
";
                var detailSqlParts = new List<string>();
                for (int i = 0; i < dto.Details.Count; i++)
                {
                    detailSqlParts.Add($"INSERT INTO SalesOutboundDetail (SalesOutboundId, MaterId, CopyTradCode, Num, Remark, CreateUser, CreateTime, IsDeleted) VALUES (@hid, @D{i}_MaterId, @D{i}_CopyTradCode, @D{i}_Num, @D{i}_Remark, @CreateUser, @CreateTime, false);");
                }
                var tailSql = "COMMIT; SELECT @hid AS Id;";
                var fullSql = headerSql + string.Join("\n", detailSqlParts) + tailSql;

                var param = new Dictionary<string, object?>
                {
                    ["OrderCode"] = dto.OrderCode,
                    ["OrderType"] = dto.OrderType ?? "出库单",
                    ["BusinessType"] = dto.BusinessType ?? "销售出库",
                    ["Period"] = dto.Period,
                    ["CustomerCode"] = dto.CustomerCode,
                    ["CustomerName"] = dto.CustomerName,
                    ["OrderDate"] = dto.OrderDate ?? now,
                    ["BusinessStatus"] = dto.BusinessStatus ?? "正常",
                    ["Warehouse"] = dto.Warehouse,
                    ["OrderStatus"] = dto.OrderStatus ?? "开立",
                    ["DeliveryNo"] = dto.DeliveryNo,
                    ["DeliveryType"] = dto.DeliveryType,
                    ["BusinessDept"] = dto.BusinessDept,
                    ["BusinessPerson"] = dto.BusinessPerson,
                    ["Remark"] = dto.Remark,
                    ["CreateUser"] = dto.CreateUser,
                    ["CreateTime"] = now
                };
                for (int i = 0; i < dto.Details.Count; i++)
                {
                    var d = dto.Details[i];
                    param[$"D{i}_MaterId"] = d.MaterId;
                    param[$"D{i}_CopyTradCode"] = d.CopyTradCode;
                    param[$"D{i}_Num"] = d.Num;
                    param[$"D{i}_Remark"] = d.Remark;
                }

                long newId = 0;
                try
                {
                    newId = outboundRepo.QueryFirstOrDefault<long>(fullSql, param);
                }
                catch
                {
                    outboundRepo.Execute("ROLLBACK;");
                    throw;
                }

                result.Code = APIEnums.Success;
                result.Msg = "新增销售出库成功";
                result.Data = newId;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "新增销售出库失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "新增销售出库失败";
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
